package com.tvsinfo.jdk.demo.case4_stream;

import com.tvsinfo.jdk.demo.case2_function_interface.dto.Car;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 流的扁平化
 */
public class Stream4_flat implements Stream_Create_List {

    public void streamFlat() {
        List<Car> cars = getList();

        //方式1：
        System.out.println("分区-1--------------------------------");
        List<List<String>> list = cars.stream().map(car -> car.getAgency()).collect(Collectors.toList());
        System.out.println(list);


        //方式2：将多个List合并成一个List
        System.out.println("扁平化1：--------------------------------");
        List<String> list2 = cars.stream().flatMap(car -> car.getAgency().stream()).distinct().collect(Collectors.toList());
        System.out.println(list2);


        //方式3：将多个List合并成一个List
        System.out.println("扁平化2：--------------------------------");
        List<String> list3 = cars.stream().map(car -> car.getAgency().toArray(new String[0])).flatMap(Arrays::stream).distinct().collect(Collectors.toList());
        System.out.println(list3);

        //方式4:多次扁平化
        System.out.println("扁平化3：--------------------------------");
        List<String> list4 = cars.stream().flatMap(car -> car.getAgency().stream().map(s -> new String[]{s})).flatMap(Arrays::stream).distinct().collect(Collectors.toList());
        System.out.println(list4);
    }
}
